﻿using System.Collections.Generic;
using System.Web.Mvc;
using StoreDemo.Domain.Entities;
using StoreDemo.Domain.Services;

namespace StoreDemo.Web.Controllers
{
    public class ProductsController : Controller
    {
        private readonly IProductService _productService;

        public ProductsController(IProductService productService)
        {
            _productService = productService;
        }

        public ViewResult Index()
        {
            IEnumerable<Product> allProducts = _productService.GetAllProducts();
            return View(allProducts);
        }

        public ViewResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Product product)
        {
            if(ModelState.IsValid)
            {
                _productService.Save(product);
                return RedirectToAction("Index");
            }
            return View(product);
        }

        public ViewResult Edit(int productId)
        {
            Product product = _productService.Get(productId);
            return View(product);
        }

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if(ModelState.IsValid)
            {
                _productService.Update(product);
                return RedirectToAction("Index");
            }
            return View(product);
        }

        public RedirectToRouteResult Delete(int idOfProductToBeDeleted)
        {
           _productService.Delete(idOfProductToBeDeleted);
            return RedirectToAction("Index");
        }
    }
}